﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using iCollect.Constants;
using Modbus.Device;
using System.Collections;
using iCollect.Events;
using iCollect.util;

namespace iCollect.CustomComponent
{
    public partial class BaseDeviceMonitor : UserControl
    {
        private Random random = new Random();
        public virtual event EventHandler RaiseCustomEvent;

        public BaseDeviceMonitor()
        {
            InitializeComponent();
        }
 

        public void timer1_Tick()
        {
            foreach (Control c1 in this.Controls)
            {
                string c1Type = c1.GetType().ToString();
                if (c1Type == "System.Windows.Forms.TextBox")
                {
                    TextBox tx = (TextBox)c1;
                    if (tx.Name.Substring(0, 2) == "tb")
                    {
                        continue;
                    }
                    tx.Text = ((int)(random.NextDouble() * 10.0)).ToString();
                }
            }
            readFromDevice();
            displayValue();
        }

        protected virtual void readFromDevice()
        {
            ModbusSerialRtuMasterReadRegisters();
        }

        protected virtual void displayValue()
        {
        }

        /// <summary>
        /// Simple Modbus serial RTU master write holding registers example.
        /// </summary>
        public void ModbusSerialRtuMasterReadRegisters()
        {
            string key = "";
            String channelStr = "";

            try
            {
                using (SerialPort port = new SerialPort(GlobalConstants.port))
                {
                    // configure serial port
                    port.BaudRate = 9600;
                    port.DataBits = 8;
                    port.Parity = Parity.None;
                    port.StopBits = StopBits.One;
                    port.Open();

                    // create modbus master
                    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                    byte slaveId = GlobalConstants.slaveID;
                    ushort startAddress;//= 40;
                    ushort numRegisters;// = 5;
                    ushort[] registers;


                    for (int i = 0; i < tbMap.Keys.Count; i++)
                    {
                        key = tbMap.Keys.ElementAt(i);
                        channelStr = GlobalConstants.channelMap[key].ToString();
                        startAddress = (ushort)(int.Parse(channelStr.Substring(1)) - 1);
                        numRegisters = 1;
                        registers = master.ReadInputRegisters(slaveId, startAddress, numRegisters);

                        ushort channelValue = registers[0];
                        setTextBoxValue(channelValue, key);
                        List<ArrayList> itemList = GlobalConstants.currentData[key];
                        ArrayList timeValue = new ArrayList();
                        timeValue.Add(DateTime.Now);
                        timeValue.Add(channelValue);
                        itemList.Add(timeValue);

                        if (itemList.Count > GlobalConstants.displayCount)
                        {
                            itemList.RemoveAt(0);
                        }
                    }

                    port.Close();
                }
            }
            catch (Exception ex)
            {
                OnRaiseCustomEvent(this, new CustomEventArgs(CustomEventArgs.EXCEPTION_STATUS, 0));
                string msg = "端口:" + GlobalConstants.port + " 通道ID:" + key + " 通道地址:" + channelStr + "\n";
                popupMessage(msg + ex.Message);
            }

        }

        protected virtual void setTextBoxValue(Double channelValue, string key)
        {
            TextBox tb = tbMap[key];
            tb.Text = channelValue.ToString();
            if (!GlobalConstants.channelAlert.ContainsKey(key))
            {
                return;
            }
            ArrayList al = GlobalConstants.channelAlert[key];
            int alert1 = (int)al[0];
            int alert2 = (int)al[1];
            int stop1 = (int)al[2];
            int stop2 = (int)al[3];
            if (alert1 > alert2 || stop1 > stop2 || 
                alert1 < stop1 || alert2 > stop2)
            {
                return;
            }
            else
            {
                if ((channelValue >= alert2 && channelValue < stop2) ||
                    (channelValue <= alert1 && channelValue > stop1))
                {
                    tb.BackColor = Color.Yellow;
                    OnRaiseCustomEvent(this, new CustomEventArgs(CustomEventArgs.ALERT_STATUS, 0));
                }
                else if (channelValue >= stop2 || channelValue <= stop1)
                {
                    tb.BackColor = Color.Salmon;
                    OnRaiseCustomEvent(this, new CustomEventArgs(CustomEventArgs.STOP_STATUS, 0));
                }
                else
                {
                    tb.BackColor = Color.GreenYellow;
                }
            }
        }

        private void popupMessage(string msg)
        {
            DialogResult MsgBoxResult;//设置对话框的返回值
            MsgBoxResult = MessageBox.Show(msg,//对话框的显示内容
            "提示",//对话框的标题
            MessageBoxButtons.OK,//定义对话框的按钮，这里定义了YSE和NO两个按钮
            MessageBoxIcon.Exclamation,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号
            MessageBoxDefaultButton.Button1);//定义对话框的按钮式样
        }

        protected virtual void OnRaiseCustomEvent(object sender, EventArgs e)
        {
            EventHandler handler = RaiseCustomEvent;

            // Event will be null if there are no subscribers
            if (handler != null)
            {
                handler(sender, e);
            }
        }

        protected virtual void setTBMap(object sender, EventArgs e)
        {
            createTextBoxMap();
        }

        protected Dictionary<String, TextBox> tbMap = new Dictionary<String, TextBox>();
        protected virtual void createTextBoxMap()
        {

        }

        protected void setEvent()
        {
            TextBox tb;
            foreach (Control panel in this.Controls)
            {
                if (panel is Panel)
                {
                    foreach (Control control in ((Panel)panel).Controls)
                    {
                        if (control is TextBox)
                        {
                            tb = (TextBox)control;
                            tb.Click += new System.EventHandler(OnRaiseCustomEvent);
                        }
                    }
                }

            }
        }

    }
}
